<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      
  <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  
  <!--

    Current State / TODO List

     - use pick games sceen needed WeekPickViewModel
          * we need to set up domain for this, what are we actually going to store?
     - 

  -->
  <head>
    <meta charset="utf-8">
    <title>College Football</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <!-- STYLES -->
    <link href="../../assets/css/bootstrap.css" rel="stylesheet">
    <link href="../../assets/css/datepicker.css" rel="stylesheet">
    <link href="../../assets/css/bootstrap-responsive.css" rel="stylesheet">  

    <!-- LOCAL STYLES -->
    <style type="text/css">
        body {
          padding-top: 60px;
          padding-bottom: 40px;
        }

        #alert-container {
            visibility: hidden;
        }

       .green{
          color: green;
          border-color: green;
        }

        .btnfixedmed{
          width: 150px; 
        }

    </style>

    <!-- Fav and touch icons -->
    <link rel="shortcut icon" href="../../assets/ico/favicon.ico">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="../../assets/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="../../assets/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="../../assets/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="../../assets/ico/apple-touch-icon-57-precomposed.png">
    <!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
    <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->

    <!-- JS -->
    <script src="../../assets/js/jquery-1.8.3.js"></script>
    <script src="../../assets/js/handlebars-1.0.rc.1.js" type="text/javascript" charset="utf-8"></script>
    <script src="../../assets/js/knockout-latest.debug.js"></script>
    <script src="../../assets/js/sammy.js"></script>
    <script src="../../assets/js/datepicker.js"></script>
    <script src="../../assets/js/bootstrap.js"></script>
    <script src="../../assets/js/bootstrap-alert.js"></script>
  
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"]});
        google.load('visualization', '1', {packages:['table']});
        google.load('visualization', '1.0', {'packages':['controls']});

        /****************************
         * Standard Options 
         * set up standard options for the google charts and tables
         *
         ***/
        var standardColumnChartOptions = {bar : {groupWidth: 35}, chartArea: {width: '50%'},  width: 400, height: 200}; 
        var standardBarChartOptions = {chartArea: {width: '65%'},  width: 800, height: 250};
        var standardPieChartOptions = {width: 400, height: 150, backgroundColor: '#FFFFFF'  };
        var googleTableCSS = {'headerCell': 'ui-state-default', 'tableCell': 'td',  'oddTableRow': 'odd' ,};
        var standardTableOptions =  {showRowNumber: false, sort:'disable'};

        var drawTable = function(tablejson, divPreFix, additionalopts) {
                  console.log("drawTable : " + divPreFix);
                  console.log("tablejson : " + tablejson);
                  console.log("tablejson : " + !jQuery.isEmptyObject(tablejson));

                  if(tablejson && !jQuery.isEmptyObject(tablejson))
                  {
                    console.log("google : " + google);

                    //google.setOnLoadCallback(function(){
                                 console.log("drawTable : setOnLoadCallback");
                                //Create DataTable For Display - sort by first column
                                //
                                var d = new google.visualization.DataTable(tablejson ,0.6);
                                
                                console.log("drawTable : " + d);
                                n
                                d.sort([{column: 0}]);
                                var tableDiv = divPreFix + 'Table';
                                var tableoptions = jQuery.extend({},this.standardTableOptions, additionalopts);
                                tableoptions.cssClassNames = googleTableCSS;
                                console.log("drawTable : tableoptions : " + tableoptions);
                                //Draw Table  
                                //
                                var table = new google.visualization.Table(document.getElementById(tableDiv) );
                                table.draw(d,tableoptions);   
                    //});
                  }
        };  

    </script>

    <!--
    /*************************
     * HANDLES BARS TEMPLATES
     *
     *************************
    -->
    <!-- TOP NAVIGATION - START -->
    <script id="top-navigation" type="text/x-handlebars-template">
          <div class="navbar-inner">
            <div class="container">
              <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </a>
              <a class="brand" href="#/home">College Football</a>
              <div class="nav-collapse collapse">
                {{#unless disablenav}}
                  <ul class="nav">
                        <li>
                         <a href="#/signout">Sign out</a>  
                        </li>
                      {{#if makeYourPicks}}
                        <li class="active">
                      {{else}}  
                        <li>
                      {{/if}}
                          <a href="#/playerweeks">Your Picks</a>
                        </li>

                      {{#if admin}}
                        <li class="active">
                      {{else}}  
                        <li>
                      {{/if}}
                        <a href="#/weeks">Admin</a></li>
                  </ul>
                {{/unless}}
              </div>
            </div>
          </div>
    </script>
    <!-- TOP NAVIGATION - END -->

    <!-- SUB NAVIGATION - START --> 
    <script id="sub-navigation" type="text/x-handlebars-template">
        {{#unless disablesubnav}}
        <ul class="nav nav-tabs">
              {{#if weeks}}
                <li class="active">
              {{else}}  
                <li>
              {{/if}}
                  <a href="#" data-bind="click: ADMINNAVHELPER.goToWeeksList">Weeks</a>
                </li>
              {{#if users}}
                <li class="active">
              {{else}}  
                <li>
              {{/if}}
                  <a href="#" data-bind="click: ADMINNAVHELPER.goToUsersList">Users</a>
                </li>   
              {{#if controls}}
                <li class="active">
              {{else}}  
                <li>
              {{/if}}    
                  <a href="#" data-bind="click: ADMINNAVHELPER.goToControls">Controls</a>
                </li>                                               
        </ul>
        {{/unless}}
        <h3> {{title}}</h3>
    </script>

    <!-- SUB NAVIGATION - END -->

    <!-- ADMIN LOGIN START-->
    <script id="login" type="text/x-handlebars-template">
      <div id="myCarousel" class="carousel slide">
        <div class="carousel-inner">
          <div class="item active">
            <img src="/assets/img/gt_big_banner.jpg" alt="">
            <div class="container">
              <div class="carousel-caption">
                <p class="lead">
                    Who
                </p>
              </div>
            </div>
          </div>
          <div class="item">
            <img src="/assets/img/gator_big_banner.jpg" alt="">
            <div class="container">
              <div class="carousel-caption">
                <p class="lead">
                    Will
                </p>
              </div>
            </div>
          </div>
          <div class="item">
            <img src="/assets/img/win_big_banner.jpg" alt="">
            <div class="container">
              <div class="carousel-caption">
                <p class="lead">
                    Win it All?
                </p>
              </div>
            </div>
          </div>
        </div>
        <a class="left carousel-control" href="#myCarousel" data-slide="prev">&lsaquo;</a>
        <a class="right carousel-control" href="#myCarousel" data-slide="next">&rsaquo;</a>
      </div>
      </div>
        <div class="container">
          <div class ="row">
            <div class="span6">
              <form action="#/login-form" method="post"> 
                 <label>Username</label>
                <input type="text" name="username" placeholder="username">   
                 <label>Password</label>
                <input type="password" name="password" placeholder="password">   
                <div class="container">
                  <button class="btn btn-small" type="submit">Login</button>
                </div>
              </form>
            </div>
          </div>
        </div>
    </script> 
    <!-- ADMIN LOGIN END -->

    <!--
      ******************************************************************************************************
      USER Templates
      ******************************************************************************************************
    -->

  <!-- HOME SCREEN -->
    <script id="home" type="text/x-handlebars-template">
      <div class="container">
          <div class="charttablecontainer">
            <div id="homeOverallResultsTable"></div>
          </div>
      </div>
      <div class="container">
          <button data-bind="click: drawTable" class="btn btn-small btn-success">Draw Table</button>
      </div>
    </script>
  <!-- -->

  <!-- SCOREBOARD SCREEN -->
    <script id="scoreboard" type="text/x-handlebars-template">
      <div class="container">

      </div>
      <div class="container">

      </div>
    </script>
  <!-- -->

    <!-- USER WEEK LIST  - START -->
    <script id="player-weeks-list" type="text/x-handlebars-template">
        <table class="table table-hover">
              <thead>
                  <tr>
                    <th>Week</th>
                    <th>Date Range</th>
                    <th>Winner</th>
                    <th>Loser</th>
                    <th>Your Score</th>
                    <th>Status</th>
                    <th>&nbsp;</th>
                  </tr>
                </thead>
                <tbody>
                <!-- ko foreach: weeks -->    
                  <tr>
                    <td data-bind="text: weeknumber"></td>
                    <td data-bind="text: daterange"></td>
                    <td data-bind="text: winner"></td>
                    <td data-bind="text: loser"></td>
                    <td data-bind="text: userscore"></td>                 
                    <td>
                      <!-- ko if: complete -->
                        Complete
                      <!-- /ko -->
                      <!-- ko if: active -->
                        Active
                      <!-- /ko -->                      
                    </td>
                    <td>
                        <!-- ko ifnot: active  -->
                          <!-- ko ifnot: complete -->
                            <a href="#" data-bind="click: $root.goToPlayerPicks"class="btn btn-link">Make Picks</a> 
                          <!-- /ko -->
                        <!-- /ko -->
                        <!-- ko if: complete -->
                          <a href="#" data-bind="click: $root.goToWeekScore"class="btn btn-link">Scoreboard</a> 
                        <!-- /ko -->
                    </td>
                  </tr>
                <!-- /ko -->  
                </tbody>
        </table>      
    </script>

    <!-- USER PICK WEEK LIST  - START -->
    <script id="player-picks" type="text/x-handlebars-template">
            <ul class="nav nav-pills">
              <li><a href="#" data-bind="click: $root.goToPlayerPickWeeksList" >Back to All Weeks</a></li>
            </ul>
            <table class="table table-hover">
              <thead>
                  <tr>
                    <th>Favorite</th>
                    <th>Underdog</th>
                    <th>Spread</th>
                    <th>Pick</th>
                  </tr>
                </thead>
                <tbody>
                <!-- ko foreach: games -->    
                  <tr>
                    <td data-bind="text: favorite, style: { fontWeight: favoredlocation == 'HOME' ? 'bold' : 'normal' }"></td>
                    <td data-bind="text: underdog, style: { fontWeight: favoredlocation == 'AWAY' ? 'bold' : 'normal' }"></td>
                    <td data-bind="text: spread"></td>
                    <td>
                        <div class="btn-group btn-block" data-toggle="buttons-radio">  
                          <button id="btn-favorite" type="button" data-toggle="button" data-bind="attr: {name: favorite}" class="btn btnfixedmed"><span data-bind="text: favorite"></span></button>
                          <input data-bind="value: pick" name="pick" type="hidden"/>
                          <button id="btn-underdog" type="button" data-toggle="button" data-bind="attr: {name: underdog}" class="btn btnfixedmed"><span data-bind="text: underdog"></span></button>
                        </div>
                    </td>
                  </tr>
                <!-- /ko -->  
                </tbody>
            </table>
            <div class="container">
              <button data-bind="click: $root.saveWeek" class="btn btn-small btn-primary ">Save Week</button>
              <button data-bind="click: $root.goToPlayerPickWeeksList" class="btn btn-small">Cancel</button>
            </div>              
    </script>

    <!--
      ******************************************************************************************************
      Admin Templates
      ******************************************************************************************************
    -->

    <!-- CONTROLS SCREEN -->
    <script id="controls" type="text/x-handlebars-template">
      <div class="container">
        <div id="buttondiv" class="container">
             <button data-bind="click: $root.runscore" class="btn btn-small btn-primary ">Score Weeks</button>
             <button data-bind="click: $root.createusers" class="btn btn-small btn-primary ">Load Test Users</button>
        </div>
      </div>
    </script>
    <!-- -->

    <!-- Admin Users List - START -->
    <script id="users-list" type="text/x-handlebars-template">
      <div class="container">
        <table class="table table-hover">
        <thead>
            <tr>
              <th>User Id</th>
              <th>Name</th>
              <th>Username / Email</th>
              <th>Role</th>
              <th>Password</th>
            </tr>
        </thead>
        <tbody>
          <!-- ko foreach: users -->    
          <tr>
            <td data-bind="text: userid"></td>
            <td data-bind="text: name"></td>
            <td data-bind="text: username"></td>
            <td data-bind="text: role"></td>
            <td data-bind="text: password"></td>
            <td>
              <a href="#" data-bind="click: $root.goToUser"class="btn btn-link">Edit</a>
              <a href="#" data-bind="click: $root.removeUser"><i class="icon-remove"></i></a>  
            </td>
          </tr>
          <!-- /ko -->  
        </tbody>
        </table>
      </div>
      <!-- CONTAINER - Table of Users - END -->
      <!-- BUTTONS - START -->
      <div class="container">
        <button data-bind="click: goToUser" class="btn btn-small btn-success">Add / Create a User</button>
        <button data-bind="click: showJSON" class="btn btn-small btn-warning">Show JSON</button>
      </div>
      <!-- BUTTONS - END -->
    </script>
    <!-- Admin Users List - END -->

    <!-- User Create / Edit START-->
    <script id="user-edit" type="text/x-handlebars-template">
      <div class="container well">
        <form data-bind="submit: saveUser">
          <label>Id</label>
          <input data-bind="value: userid" type="text" placeholder="">   
          <label>Name</label>
          <input data-bind="value: name" type="text" placeholder="First Last">
          <label>Username / Email</label>
          <input data-bind="value: username" type="text" placeholder="football@awesome.com">
          <label>Role</label>
          <select data-bind="options: $root.availableRoles, value: role, optionsText: 'label'" size=1></select>
          <label>Password</label>
          <input data-bind="value: password" type="text" placeholder="secret password">      
          <div class="container">
            <button data-bind="click: saveUser" class="btn btn-small btn-warning">Save</button>
            <button data-bind="click: cancel" class="btn btn-small">Cancel</button>
          </div>
        </form>
      </div> 
    </script>
    <!-- User Create / Edit END -->

    <!-- CONTENT - WEEK EDIT  - START -->
    <script id="week-edit" type="text/x-handlebars-template">
        <div class="container well">
        <form>
        <fieldset>
          <div class="clearfix">
          <div class="row">
            <div class="span2">
              <label>Week Number</label>
              <label class="checkbox">
                <input data-bind="checked: published"  type="checkbox">
                Publish this Week
              </label>              
            </div>
            <div class="span2">
              <input data-bind="value: weeknumber" maxlength="2" class="span1" type="text"/>
            </div>
          </div>
          <BR>
          <div class="row"> 
            <div class="span2">
              <label>Favorite</label>
            </div>
            <div class="span2">
              <label>Underdog</label>
            </div>
            <div class="span1">
              <label>Spread</label>
            </div>
            <div class="span2">
              <label>Date</label>
            </div>
            <div class="span2">
              <label>Time</label>
            </div>
            <div class="span2">
              <label>Favored Is</label>
            </div>
            <div class="span1">
              &nbsp;
            </div>
          </div>
          <!-- ko foreach: games -->
            <div class="row"> 
              <div class="span2">
                <input data-bind="value: favorite"  class="span2 team" type="text" placeholder="Team Name"/>
              </div>
              <div class="span2">
                <input data-bind="value: underdog"  class="span2 team" type="text" placeholder="Team Name"/>
              </div>
              <div class="span1">
                <input data-bind="value: spread" maxlength="2" class="span1" type="text"/>
              </div>
              <div class="span2">
                <input data-bind="value: gamedate" data-datepicker="datepicker" class="span2" id="inputIcon" type="text" placeholder="MM/DD/YYYY" />
              </div>
              <div class="span2">
                <select data-bind="options: $root.availableTimes, value: time, optionsText: 'label'"  class="span2" size=1></select>
              </div>
              <div class="span2"> 
                <div class="btn-group" data-toggle="buttons-radio">  
                  <button id="btn-home" type="button" data-toggle="button" name="HOME" value="" class="btn">Home</button>
                  <input data-bind="value: favoredlocation" name="favoredlocation" type="hidden"/>
                  <button id="btn-away" type="button" data-toggle="button" name="AWAY" value="" class="btn">Away</button>
                </div>
              </div>
              <div  class="span1">
                <a href="#" data-bind="click: $root.removeGame"><i class="icon-remove"></i></a> 
              </div>
            </div>
          <!-- /ko -->
        </fieldset>
        </form>
        </div>
        <div class="container">
          <button data-bind="click: addGame" class="btn btn-small btn-success">Create another Game</button>
          <button data-bind="click: saveWeek" class="btn btn-small btn-primary ">Save Week</button>
          <button data-bind="click: cancel" class="btn btn-small">Cancel</button>
        </div>
    </script>

    <!-- WEEK LIST  - START -->
    <script id="weeks-list" type="text/x-handlebars-template">
        <table class="table table-hover">
              <thead>
                  <tr>
                    <th>Week</th>
                    <th>Date Range</th>
                    <th>Winner</th>
                    <th>Score</th>
                    <th>Loser</th>
                    <th>Score</th>
                    <th>Average</th>
                    <th>Status</th>
                    <th>Controls</th>
                  </tr>
                </thead>
                <tbody>
                <!-- ko foreach: weeks -->    
                  <tr>
                    <td data-bind="text: weeknumber"></td>
                    <td data-bind="text: daterange"></td>
                    <td data-bind="text: winner"></td>
                    <td data-bind="text: winnercount"></td>
                    <td data-bind="text: loser"></td>
                    <td data-bind="text: losercount"></td>
                    <td data-bind="text: average"></td>
                    <td>
                      <!-- ko if: published -->
                        Published  
                      <!-- /ko -->
                      <!-- ko if: complete -->
                        Complete
                      <!-- /ko -->
                    </td>
                    <td>
                      <a href="#" data-bind="click: $root.goToWeek" class="btn btn-link">Edit</a>
                      <a href="#" data-bind="click: $root.goToWeekScore"class="btn btn-link">Score</a>
                      <a href="#" data-bind="click: $root.removeWeek"><i class="icon-remove"></i></a>   
                    </td>
                  </tr>
                <!-- /ko -->  
                </tbody>
        </table>
        <div id="buttondiv" class="container">
            <a href="#" data-bind="click: $root.goToWeek" class="btn btn-small btn-success">Add / Create a Week</a>
        </div>
    </script>

    <!-- WEEK SCORE  - START -->
    <script id="week-score" type="text/x-handlebars-template">
      <div class="container well">
      <form>
      <fieldset>
        <div class="clearfix">
        <div class="row">
          <div class="span2">
            <label>Week Number</label>
          </div>
          <div class="span1">
            <span data-bind="text: weeknumber" class="span1 uneditable-input" />
          </div>
        </div>
        <div class="row"> 
          <div class="span2"><label>Score</label></div>      
          <div class="span2"><label>Favorite</label></div>
          <div class="span2"><label>Underdog</label></div>
          <div class="span1"><label>Spread</label></div>
          <div class="span2"><label>Date</label></div>
          <div class="span1"><label>Time</label></div>
          <div class="span2"><label>Favored Is</label></div>
        </div>
        <!-- ko foreach: games -->
          <div class="row datarow"> 
            <div class="span2">
              <input data-bind="value: scorefavored"  class="span1 input" name="sfav" type="text"/>
              <input data-bind="value: scoreunderdog" class="span1 input" name="sund" type="text"/>
              <input data-bind="value: winner" type="hidden" class="winner"/>
            </div>        
            <div class="span2">
              <span data-bind="text: favorite"  class="span2 uneditable-input favorite" type="text"/>
            </div>
            <div class="span2">
              <span data-bind="text: underdog"  class="span2 uneditable-input underdog" type="text"/>
            </div>
            <div class="span1">
              <span data-bind="text: spread" maxlength="2" class="span1 uneditable-input spread" type="text"/>
            </div>
            <div class="span2">
              <span data-bind="text: gamedate" class="small uneditable-input" type="text" />
            </div>
            <div class="span1">
              <span data-bind="text: time.label" maxlength="2" class="span1  uneditable-input" type="text"/>
            </div>
            <div class="span2">
              <span data-bind="text: favoredlocation" maxlength="2" class="span1 uneditable-input" type="text"/>
            </div>
          </div>
        <!-- /ko -->
      </fieldset>
      </form>
      </div> <!-- /container -->
      <div class="container">
        <button data-bind="click: saveGameScores" class="btn btn-small btn-primary ">Save Week</button>
        <button data-bind="click: cancel" class="btn btn-small">Cancel</button>
      </div>
    </script>


   <!-- MESSAGE - START -->
  <script id="message" type="text/x-handlebars-template">
        <div class="alert {{alertclass}} fade in">
              <button type="button" class="close" data-dismiss="alert">&times;</button>
              <p>{{alertmessage}}</p>
        </div>
  </script>

  </head>           
  <body>
      <!-- target divs for templates START -->

      <div id="navigationdiv" class="navbar navbar-inverse navbar-fixed-top"></div>
      <div id="messagediv" class="container"></div>
      <div id="subnavigationdiv" class="container"></div>
      <div id="contentdiv" class="container"></div>
      
      <!-- target divs for templates END -->

<!-- 

 /*******************************************************************************************************************************************************************************
  *******************************************************************************************************************************************************************************
  *******************************************************************************************************************************************************************************
  * MODELS - Knockout
  * 
  *******************************************************************************************************************************************************************************
  *******************************************************************************************************************************************************************************
  ******************************************************************************************************************************************************************************/
 -->
<script>

  // ******************************************************************************************************************
  // ControlViewModel
  //
  // Admin System Controls screen - for overall system info display and controls for running tests
  //
  //
  function ControlViewModel()
  {
    cflog("ControlViewModel : init : ");
    var self = this;   

    // Model Construction
    // take api results and build model
    self.loadscoreresults = function(data){
      CFBMESSAGE.success("Player Scores Updated");
      cflog("loadScoreResults");
      cflog(data);
    };

    // Model Construction
    // take api results and build model
    self.usercreateresults = function(data){
      CFBMESSAGE.success("Users Created");
      cflog("usercreateresults");
      cflog(data);
    };

    self.createusers = function() {
      cflog("ControlViewModel : createusers ");
      CFBAPI.get('/test/createtestusers', 
          function (result) {self.usercreateresults(result);},
          function (XMLHttpRequest, textStatus, errorThrown) {
              CFBMESSAGE.error("Could not createtestusers");
              cflog(textStatus);
              cflog(errorThrown);
      });
      return true;

    }

    self.runscore = function() {
      cflog("ControlViewModel : runscore ");
      CFBAPI.get('/admin/run/scores', 
          function (result) {self.loadscoreresults(result);},
          function (XMLHttpRequest, textStatus, errorThrown) {
              CFBMESSAGE.error("Could not run scores");
              cflog(textStatus);
              cflog(errorThrown);
      });
      return true;
    };

  }

  // ******************************************************************************************************************
  // Weeks Model 
  //
  // handles list of weeks, results are shown if applicable, edit, delete controls presented
  //
  //
  function WeeksViewModel() 
  {
      cflog("WeeksViewModel : init : ");

      var self = this;   
      self.weeks = ko.observableArray([]);
      
      self.showJSON = function() {
        var jsonData = ko.toJSON(self);
        cflog(jsonData);
      };

      self.removeWeek = function(week) {
        cflog('remove week : ' + week.weeknumber);
        CFBAPI.get('/admin/week/delete/' + week.weeknumber, 
            function (result) {
              CFBMESSAGE.success("Week Removed!");
              self.weeks.remove(week);
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not remove Week");
                cflog(textStatus);
                cflog(errorThrown);
        });
      };

      self.loadWeeks = function() {
        cflog("WeeksViewModel : loadWeeks ");
        CFBAPI.get('/admin/weeks', 
            function (result) {self.loadWeeksFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load list of Weeks");
                cflog(textStatus);
                cflog(errorThrown);
        });
        return true;
      };

      // Model Construction
      // take api results and build model
      self.loadWeeksFromServer = function(data){
        cflog("loadweeksfromserver");
        cflog(data);
        self.weeks(data);
      };

      self.goToWeek = function(week) { 
          cflog('goToWeek : ' + week.weeknumber);
          var wknum = week.weeknumber;

          if(typeof week.weeknumber == 'undefined')
          {
            wknum = -1;
          }

          location.hash = '/week/' + wknum; 
      };

      self.goToWeekScore = function(week) {
          cflog('goToWeekScore');
          location.hash = '/week/score/' + week.weeknumber; 
      };

      // INIT
      // 

      self.loadWeeks();
  };

  // ******************************************************************************************************************
  // GamesViewModel  - 
  // Add / Edit / Delete Games of the Week
  // For handling list of games of the week
  // Pick matchups, set the spread, home team, time, etc
  //
  
  function Game(favorite, underdog, spread, gamedate, favoredlocation, time) 
  {
        var self = this;
        self.favorite = ko.observable(favorite);
        self.underdog = ko.observable(underdog);  
        self.spread = ko.observable(spread);  
        self.gamedate = ko.observable(gamedate);
        self.favoredlocation = ko.observable(favoredlocation);  
        self.time = ko.observable(time);  
  };

  function refreshGamesViewModel()
  {
    var allTeams = ["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut","Delaware","Florida","Georgia","Hawaii","Idaho","Illinois","Indiana","Iowa","Kansas","Kentucky","Louisiana","Maine","Maryland","Massachusetts","Michigan","Minnesota","Mississippi","Missouri","Montana","Nebraska","Nevada","New Hampshire","New Jersey","New Mexico","New York","North Dakota","North Carolina","Ohio","Oklahoma","Oregon","Pennsylvania","Rhode Island","South Carolina","South Dakota","Tennessee","Texas","Utah","Vermont","Virginia","Washington","West Virginia","Wisconsin","Wyoming"];
    
    // css consts
    var selectedRadioCSS = 'btn btn-info';
    var notSelectedRadioCSS = 'btn';

    // set up cals for all date fields
    $('[data-datepicker]').datepicker();

     // Radio Button - Hidden Input - Toggle
     // check our toggle buttons and hidden fields are synched up
     var buttons = $('.btn-group').each( function(index, el){
              var hidden = $(el).find('input');
              var match = hidden.siblings('button[name="'+ hidden.val() + '"]').attr('class', selectedRadioCSS);
              var notmatch = match.siblings('button').attr('class', notSelectedRadioCSS);
                });

     $('.team').typeahead({source: allTeams, items:5});

      // TOGGLE RADIO BUTTONS - onClick
      // for home and away
      // will work on all added rows
      $("form").delegate(".btn", "click", function() {
          var clicked = $(this);                //who was clicked
          var hidden = clicked.siblings('input'); 

          if(clicked.attr('name') != hidden.val())
          {
            var sibling = clicked.siblings('button');   //find button that was not clicked
            var currentCSS = clicked.attr('class');     //get clicked existing style/state
            var newCSS = sibling.attr('class');       //get not clicked existing style/state

            clicked.attr('class', newCSS);          //flip styles
            sibling.attr('class', currentCSS);

            //update hidden prop and switch values
            hidden.val(clicked.attr('name'));
            hidden.trigger("change");           //let ko know we changed hidden value     
          }
      });
  };

  function GamesViewModel(weeknumber) 
  {
      var self = this;   

      cflog("GamesViewModel : initialized : " + weeknumber);

      // FILTER MODEL ITEMS
      var MODEL_COLS = ["weeknumber", "games", "favorite", "underdog", "spread", "favoredlocation", "gamedate", "time", "label", "value", "scorefavored", "scoreunderdog", "winner", "completed", "published" ];
      
      // CONSTANTS
      //
      self.availableTimes = [
          { label: "12:00", value:  "12:00" },
          { label: "3:30", value: "15:30" },
          { label: "7:30", value: "17:30" }
      ]; 

      // OBSERVABLE DATA
      //
      self.weeknumber = ko.observable();
      self.games = ko.observableArray([]);
      self.published = ko.observable();

      /********** Actions / Helpers ***********/

      //return only the json we need from the model
      //
      self.cleanJSON = function()
      {
        var jsonData = ko.toJSON(self, MODEL_COLS);
        return jsonData;
      }

      //
      // ACTIONS
      //
      self.addGame = function() {
        self.games.push(new Game("","","","","HOME",""));
        refreshGamesViewModel();
      };
     
     // REMOVE
     //
      self.removeGame = function(game) {
       self.games.remove(game)
      };

      // LOAD
      //
      self.loadWeek = function (weeknumber) { 
          CFBAPI.get('/admin/week/' + weeknumber, 
            function (result) {self.parseWeekFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load Week");
                cflog(textStatus);
                cflog(errorThrown);
            });

        return true;
      };

      // Model Constructio
      // take api results and build model
      self.parseWeekFromServer = function(data){
        cflog("parseweekfromserver");
        cflog(data);
        self.games(data.games);
        self.weeknumber(data.weeknumber);
        self.published(data.published);
        refreshGamesViewModel();  
      };

      // SAVE
      //
      self.saveWeek = function() {
          cflog(ko.toJSON(self));
          var jsonData = self.cleanJSON();

          cflog(jsonData);

          CFBAPI.post('/admin/week/save', jsonData, 
            function (result) { 
              cflog(result);
              CFBMESSAGE.success("Week Saved!");
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Failed to save Week");
                cflog(textStatus);
                cflog(errorThrown);
            });
          
        return true;
      };

      // CANCEL
      //
      self.cancel = function() {
          cflog('GamesViewModel : cancel');
          ADMINNAVHELPER.goToWeeksList()
      };

      // INIT 
      //
      self.loadWeek(weeknumber);
  };

  // ******************************************************************************************************************
  // USER View Models
  //

  function UserViewModel() 
  {    
    var self = this;
    var serverJSON = '{"userid":"1", "name":"Mark Conlin", "username":"mark.conlin@gmail.com", "role":"Admin", "password":"password" }';
    self.userid =  ko.observableArray();
    self.name =  ko.observableArray();
    self.username =  ko.observableArray();
    self.role =  ko.observableArray();
    self.password =  ko.observableArray();

    // Valid Roles
    //
    self.availableRoles = [
      { label: "Admin", value:  "Admin" },
      { label: "Player", value: "Player" }
    ]; 

    // SAVE USER 
    //
    self.saveUser = function() 
    {
      var jsonData = ko.toJSON(self);
      cflog(jsonData);
    }

    // CANCEL
    //
    self.cancel = function() 
    { 
      cflog( "Cancel User Edit Called" );
      ADMINNAVHELPER.goToUsersList();
    };

    // LOAD USER
    // TODO : load user from server call
    //
    self.loadUser = function() 
    {
      cflog( "Load User Called" );
      var someJSON = serverJSON;
      var parsed = JSON.parse(someJSON);
      self.userid( parsed.userid );
      self.name( parsed.name );
      self.role ( parsed.role );
      self.password( parsed.password );
      self.username( parsed.username );

    }
  };

  // ******************************************************************************************************************
  // USERS LIST View Model
  //
  function UsersViewModel() 
  {
      var self = this;   
      var serverJSON = '{"users":[{"userid":"1", "name":"Mark Conlin", "username":"mark.conlin@gmail.com", "role":"Admin", "password":"password" }, {"userid":"2", "name":"Lelia Conlin", "username":"leliaconlin@gmail.com", "role":"Admin", "password":"password2" }]}';
      
      self.users = ko.observableArray([]);

      // Valid Roles
      //
      self.availableRoles = [
        { label: "Admin", value:  "Admin" },
        { label: "Player", value: "Player" }
      ]; 

      // Behaviours
      //    

      // ADD / EDIT USER
      //
      self.goToUser = function(user) { 
          cflog('goToUser');
          location.hash = '/user/' + user.userid; 
      };

      // Show JSON
      //
      self.showJSON = function() 
      {
        var jsonData = ko.toJSON(self);
        //cflog(jsonData);
        //ko.utils.postJson("http://localhost:8888/test/in", {"test":"this is my test"});
        self.testPost();
      };

      self.testPost = function () {
          //var jsonData = ko.toJSON(self);
          
          var jsonData = {"users":[{"id":"1","username":"a","role":"ADMIN","password":"ppwd"},{"id":"2","username":"b","role":"PLAYER","password":"ppwd"}]};
          var jsonDataSingle = {"id":"","username":"","role":"","password":""};
          cflog(jsonData);

          $.ajax({
            type: "POST",
            url: 'http://localhost:8888/test/in',
            data: JSON.stringify(jsonData.users),
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                cflog(result);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                cflog(textStatus);
                cflog(errorThrown);
            }
        });
        return true;
      };

      // Remove User
      //
      self.removeUser = function(usertoremove) 
      {
        self.users.remove(usertoremove);
        //
        // TODO - Ajax call to remove user - fail silently
        //
      };

      self.loadUsers = function() 
      {
        var someJSON = serverJSON;
        var parsed = JSON.parse(someJSON);

        self.users(parsed.users);
      }
  };

  // ******************************************************************************************************************
  // PICK WEEK 
  // Model for picking games of the week
  //

  //refreshPickViewModel
  //
  function refreshPickViewModel()
  {
    cflog("refreshPickViewModel : start");
    // css consts
    var selectedRadioCSS = 'btn btn-info btnfixedmed';
    var notSelectedRadioCSS = 'btn btnfixedmed';

     // Radio Button - Hidden Input - Toggle
     // check our toggle buttons and hidden fields are synched up
     var buttons = $('.btn-group').each( function(index, el){
              var hidden = $(el).find('input');
              var match = hidden.siblings('button[name="'+ hidden.val() + '"]').attr('class', selectedRadioCSS);
              var notmatch = match.siblings('button').attr('class', notSelectedRadioCSS);
                });

      // TOGGLE RADIO BUTTONS - onClick
      // for home and away
      // will work on all added rows
      $("table").delegate(".btn", "click", function() {
          var clicked = $(this);                //who was clicked
          var hidden = clicked.siblings('input'); 
          
          if(clicked.attr('name') != hidden.val())
          {
            var sibling = clicked.siblings('button');   //find button that was not clicked
            var currentCSS = clicked.attr('class');     //get clicked existing style/state
            var newCSS = sibling.attr('class');       //get not clicked existing style/state

            clicked.attr('class', selectedRadioCSS);          //clicked gets lite up
            sibling.attr('class', notSelectedRadioCSS);

            //update hidden prop and switch values
            hidden.val(clicked.attr('name'));
            hidden.trigger("change");           //let ko know we changed hidden value     
          }
      });
  };

  function WeekPickViewModel(weeknumber) {

     var self = this;   
     self.games = ko.observableArray([]);
     self.weeknumber = ko.observable();
     self.username = ko.observable();
     self.complete = ko.observable();

      // FILTER MODEL ITEMS
      //var MODEL_COLS = ["username", "weeknumber", "games", "favorite", "underdog", "spread", "favoredlocation", "pick" ];
      var MODEL_COLS = ["username", "weeknumber", "games", "favorite", "underdog", "spread", "favoredlocation", "pick"];

      // Model Construction
      // take api results and build model
      self.parseWeekFromServer = function(data){
        cflog("WeekPickViewModel : parse pickweek from server");
        cflog(data);
        self.games(data.games);
        self.weeknumber(data.weeknumber);
        self.username(data.username);
        self.complete(data.complete);
        refreshPickViewModel();  
      };

      //return only the json we need from the model
      //
      self.cleanJSON = function()
      {
        var jsonData = ko.toJSON(self, MODEL_COLS);
        return jsonData;
      }

      // LOAD
      //
      self.loadWeek = function (weeknumber) { 
          CFBAPI.get('/player/pickweek/' + weeknumber, 
            function (result) {self.parseWeekFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load Week");
                cflog(textStatus);
                cflog(errorThrown);
            });

        return true;
      };

      // SAVE
      //
      self.saveWeek = function() {
          var jsonData = self.cleanJSON();

          cflog(jsonData);

          CFBAPI.post('/player/pickweek/picks/save', jsonData, 
            function (result) { 
              cflog(result);
              CFBMESSAGE.success("Your picks Were saved!");
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Failed to save picks");
                cflog(textStatus);
                cflog(errorThrown);
                      });


            return true;
      };

      // Behaviours   
      // Set hash to trigger routes - weeks scores or make picks
      //
      self.goToPlayerPickWeeksList = function() { 
          cflog('goToPlayerPickWeeksList : ');
          location.hash = '/playerweeks'; 
      };


      // INIT 
      //
      cflog("WeekPickViewModel : init : " + weeknumber);
      self.loadWeek(weeknumber);
  };

  // ***************************************************************************************************************************************************** //

  // ******************************************************************************************************************
  // Player Home 
  //
  // Show current scores grid
  //
  function PlayerHomeViewModel() 
  {
      cflog("PlayerHomeViewModel : init : ");
      var self = this;  


        //TODO call google here
        //

        //INIT
        //

        self.drawTable = function() {

              var overallresults = { "cols" : [ { "id" : "task",
                                                  "label" : "Task",
                                                  "type" : "string"
                                                },
                                                { "id" : "hours",
                                                  "label" : "Hours per Day",
                                                  "type" : "number"
                                                }
                                              ],
                                            "rows" : [ { "c" : [ { "p" : { "style" : "border: 7px solid orange;" },
                                                        "v" : "Work"
                                                      },
                                                      { "v" : 11 }
                                                    ] },
                                                { "c" : [ { "v" : "Eat" },
                                                      { "v" : 2 }
                                                    ] },
                                                { "c" : [ { "v" : "Commute" },
                                                      { "f" : "2.000",
                                                        "v" : 2
                                                      }
                                                    ] }
                                              ]
                                          };

              cflog(overallresults);                   
              drawTable(overallresults, 'homeOverallResults', null);

      };
  };


  // ******************************************************************************************************************
  // ScoreboardViewModel 
  //
  // Show current scores grid
  //
  function ScoreboardViewModel(weeknumber) 
  {
      cflog("ScoreboardViewModel : init : ");
      var self = this;  
      self.gamescores = ko.observableArray([]);

      self.loadScores = function(weeknumber) {
        cflog("ScoreboardViewModel : loadScores : " + weeknumber);
        CFBAPI.get('/player/scoreboard/' + weeknumber, 
            function (result) {self.loadScoresFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load scoreboard");
                cflog(textStatus);
                cflog(errorThrown);
        });
        return true;
      };

      // Model Construction
      // take api results and build model
      self.loadScoresFromServer = function(data){
        cflog("loadweeksfromserver");
        cflog(data);
        self.gamescores(data);
      };

      //INIT
      //
      
      self.loadScores(weeknumber);
  };

  // ******************************************************************************************************************
  // Player Weeks Model 
  //
  // handles list of weeks, results are shown if applicable, edit, delete controls presented
  //
  function PlayerWeeksViewModel() 
  {
      cflog("PlayerWeeksViewModel : init : ");

      var self = this;   
      self.weeks = ko.observableArray([]);
      
      self.showJSON = function() {
        var jsonData = ko.toJSON(self);
        cflog(jsonData);
      };

      self.loadWeeks = function() {
        cflog("PlayerWeeksViewModel : loadWeeks ");
        CFBAPI.get('/player/weeks', 
            function (result) {self.loadWeeksFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load list of Weeks");
                cflog(textStatus);
                cflog(errorThrown);
        });
        return true;
      };

      // Model Construction
      // take api results and build model
      self.loadWeeksFromServer = function(data){
        cflog("loadweeksfromserver");
        cflog(data);
        self.weeks(data);
      };

      // Behaviours   
      // Set hash to trigger routes - weeks scores or make picks
      //
      self.goToPlayerPicks = function(week) { 
          cflog('goToPlayerPicks : ' + week.weeknumber);
          var wknum = week.weeknumber;

          if(typeof week.weeknumber == 'undefined')
          {
            cflog('goToPlayerPicks - bad week number');
          } else {
             location.hash = '/playerpicks/' + wknum; 
          }
      };

      self.goToWeekScore = function(week) {
          cflog('goToWeekScore : scoreboard');
          location.hash = '/scoreboard/' + week.weeknumber; 
      };

      // INIT
      // 

      self.loadWeeks();

  };

  // ******************************************************************************************************************
  // SCORE WEEK 
  // Admin Screen for entering scores for the games of a week
  //

  //
  // refeshGamesScoreViewModel
  function refeshGamesScoreViewModel()
  {
      // Radio Button - Hidden Input - Toggle
      // check our toggle buttons and hidden fields are synched up
      $('.datarow').each( function(){
          var winner   = $(this).find('.winner');
          
          if(typeof winner != "undefined" && winner.val() !== "")
          {
            $(".favorite, .underdog").each( function(){
              var team = $(this);
              if(team.text() == winner.val())
              {
                team.addClass("green");
                return false;
              }
            });
          }
        });

        /**********
           Spread Calc 
         As input is typed in: 
          check the values against the spread and apply green to winner
          update hidden field with value of team name

         **********/
        $("form").delegate(".row .input", "keyup", function() 
        {
          var clicked = $(this);
          var sibling = clicked.siblings('.input');   // class of input, not html of input
          var uscore;
          var fscore;
          var favwasclicked = true;

          if("sfav" == clicked.attr("name") ) 
          {
            fscore = parseInt(clicked.val());
            uscore = parseInt(sibling.val());
            favwasclicked = true;
          } else if ("sund" == clicked.attr("name") ) 
          {
            uscore = parseInt(clicked.val());
            fscore = parseInt(sibling.val());
            favwasclicked = false;
          }

          if(!isNaN(fscore) && !isNaN(uscore))
          {
            var spread = $(clicked).closest(".row").find(".spread").text();

            if(!isNaN(spread))
            {
              var diff = fscore-uscore;
              var favorite = clicked.closest(".row").find(".favorite");
              var underdog = clicked.closest(".row").find(".underdog");
              var winner   = clicked.siblings('.winner');

              if(diff >= spread)
              {
                $(favorite).addClass("green");
                $(underdog).removeClass("green");
                winner.val($(favorite).text()).change();
              } else {
                $(underdog).addClass("green");
                $(favorite).removeClass("green");
                winner.val($(underdog).text()).change();
              }
            }
          }
        });
  };

  function GamesScoreViewModel(weeknumber) 
  {
      var self = this;   
      self.weeknumber = ko.observable();
      self.games = ko.observableArray([]);
      self.published = ko.observable();
      

      // FILTER MODEL ITEMS
      var MODEL_COLS = ["weeknumber", "games", "favorite", "underdog", "spread", "favoredlocation", "gamedate", "time", "label", "value", "scorefavored", "scoreunderdog", "winner", "completed", "published" ];

      self.showJSON = function() {
        var jsonData = ko.toJSON(self);
        cflog(jsonData);
      }

      //return only the json we need from the model
      //
      self.cleanJSON = function()
      {
        var jsonData = ko.toJSON(self, MODEL_COLS);
        return jsonData;
      }

      // SAVE WEEK GAME SCORES
      //
      self.saveGameScores = function() {
          cflog(ko.toJSON(self));
          var jsonData = self.cleanJSON();
          cflog(jsonData);

          CFBAPI.post('/admin/week/score/save', jsonData, 
            function (result) { 
              cflog(result);
              CFBMESSAGE.success("Week Scores Saved!");
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Failed to save Week Scores !");
                cflog(textStatus);
                cflog(errorThrown);
            });
          
        return true;
      };

      // LOAD
      //
      self.loadWeek = function (weeknumber) { 
          CFBAPI.get('/admin/week/' + weeknumber, 
            function (result) {self.parseWeekFromServer(result);},
            function (XMLHttpRequest, textStatus, errorThrown) {
                CFBMESSAGE.error("Could not load Week");
                cflog(textStatus);
                cflog(errorThrown);
            });

        return true;
      };

      // CANCEL
      //
      self.cancel = function() {
          cflog('GamesScoreViewModel : cancel');
          location.hash = '/weeks'; 
      };

      // Model Constructio
      // take api results and build model
      self.parseWeekFromServer = function(data){
        cflog("parseweekfromserver");
        cflog(data);
        self.games(data.games);
        self.weeknumber(data.weeknumber);
        self.published(data.published);
        refeshGamesScoreViewModel();  
      };

      // INIT 
      //
      self.loadWeek(weeknumber);
  }


</script>
<script>
<!--
/********************************************************************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************************************************************
 * UTILS - get/post methods
 *
 ********************************************************************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************************************************************/
-->

  var logtoconsole = true;

  var CFBUSER = (function () 
  {
    var user = {};
    
    user.isloggedin = function() {
      if(user.apikey)
      {
        return true;
      }

      return false;
    };

    user.isadmin = function() {
      
      if(user.role === 'ADMIN')
      {
        return true;
      }

      return false;
    };

    user.init = function (data) {
        user.apikey = data.apikey;
        user.role = data.role;
        user.username = data.username;
    };
    
    return user;
  }());

  //
  //LOGGING
  //
  // use a less common namespace than just 'log'
  function cflog(msg)
  {
      // attempt to send a message to the console
      try
      {
          if(logtoconsole) { console.log(msg) };
      }
      // fail gracefully if it does not exist
      catch(e){}
  }

 // Alert Block and Messaging
 //
 var CFBMESSAGE = (function () 
 {
     var mess = {};

     mess.error = function (message) {
        showmessage("alert-error", message);
     };

     mess.info = function (message) {
        showmessage("alert-info", message);
     };

     mess.success = function (message) {
        showmessage("alert-success", message);
     };

     mess.warn = function (message) {
        showmessage("alert-warn", message);
     };

     mess.clear = function () {
        cflog("CFBMESSAGE : clear");
        hidemessage();
     }

     function hidemessage() {
          $("#messagediv").html(null);
     }

     function showmessage(alertclass, message) {
          var data = { alertclass: alertclass, alertmessage: message};
          var messagesource = $("#message").html();
          var messagetemplate = Handlebars.compile(messagesource);
          $("#messagediv").html(messagetemplate(data));
     };

     return mess;
 }());

 // API for contacting Server
 //
 var CFBAPI = (function () 
 {
    var api = {};

    api.get = function (path, successhandler, errorhandler) {

        $.ajax({
          type: "GET",
          url: path,
          contentType: "application/json; charset=utf-8",
          success: successhandler,
          error: errorhandler
        });
       return true;
    };

    api.post = function(path, datapackage, successhandler, errorhandler) {
        $.ajax({
            type: "POST",
            url: path,
            data: datapackage,
            contentType: "application/json; charset=utf-8",
            success: successhandler,
            error: errorhandler
        });
        return true;
    };

    return api;
  }());

 // ADMINHELPER - referenced by sub nav tabs on admin screens
 // navigation items used in more than one screen, so lets pull out and put in one place
 // each of the Admin modesl can just use these
 //
 var ADMINNAVHELPER = (function () 
 {
    var nav = {};

    nav.goToUsersList = function () 
              {    
                cflog('goToUsersList');
                location.hash = '/users'; 
              };

    nav.goToWeeksList = function () 
            {    
              cflog('goToWeeksList');
              location.hash = '/weeks' 
            };

    nav.goToControls = function () 
            {    
              cflog('goToControls');
              location.hash = '/controls' 
            };
 
    return nav;
  }());

</script>

<!--
/**********************************************************************************************************************************
 * Datepicker - Setup Plugin
 *
 **********************************************************************************************************************************/
-->
<script>
    /* Update datepicker plugin so that MM/DD/YYYY format is used. */

    $.extend($.fn.datepicker.defaults, 
    {
      parse: function (string) {
        var matches;
        if ((matches = string.match(/^(\d{2,2})\/(\d{2,2})\/(\d{4,4})$/))) {
          return new Date(matches[3], matches[1] - 1, matches[2]);
        } else {
          return null;
        }
      },
      format: function (date) {
        var
          month = (date.getMonth() + 1).toString(),
          dom = date.getDate().toString();
        if (month.length === 1) {
          month = "0" + month;
        }
        if (dom.length === 1) {
          dom = "0" + dom;
        }
        return month + "/" + dom + "/" + date.getFullYear();
      }
    });  
</script>


<script>
<!--
/********************************************************************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************************************************************
 * ROUTES - Sammy
 *
 *
 ********************************************************************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************************************************************
 ********************************************************************************************************************************************************************************************************************************/
-->


$.sammy(function() {

    var checkForAuthenticated = function(callback) 
    {  

       //TODO - skip if route is login submit
       //

       //TODO - check to see if apikey / user object in place
       //
       cflog("checkForAuthenticated : " + CFBUSER.isloggedin());
       callback();
    };

    var checkForAuthorized = function(callback) 
    { 

       //TODO - skip if routes is login submit or get login
       //

       //TODO - check to see if user object is Admin
       //

       cflog("checkForAuthorized : " + CFBUSER.isadmin());
       callback();
    };

    this.around(checkForAuthenticated).around(checkForAuthorized);

    //
    // handleNavigation
    // helper to perform navigation template calls
    // Can we keep navtemplate and subnavtemplate compiled vars somewhere? Safe us the hassle?
    //
    function handleNavigation(data)
    {
        CFBMESSAGE.clear();
        var navsource = $("#top-navigation").html();
        var subnavsource = $("#sub-navigation").html();
        var navtemplate = Handlebars.compile(navsource);
        var subnavtemplate = Handlebars.compile(subnavsource);
        $("#navigationdiv").html(navtemplate(data));
        $("#subnavigationdiv").html(subnavtemplate(data));
    }

    //
    // Sign Out
    //
    this.get('#/signout', function()
    {
        cflog('Signout route');
        var logout = location.protocol + "//" + location.hostname + (location.port && ":" + location.port) + "/view/index.html";  
        window.location.replace(logout);
    });


    //
    // Home Screen
    //
    this.get('#/home', function() 
    {
        cflog('Home Get route');
        //GLOBAL PAGE SETTINGS
        var data = { };

        $.extend(data, { disablenav: false, disablesubnav: true });             //top nav    
        $.extend(data, { title: "The Conlin Pool" } );                          //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#home").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new PlayerHomeViewModel());
    });

    //
    // Login Screen
    //
    this.get('#/login', function() 
    {
        cflog('Login Get route');
        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { disablenav: true, disablesubnav: true });             //top nav
        $.extend(data, { title: "" } );                                     //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#login").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));
    });

    //
    // Login Form Submit
    //
    this.post('#/login-form', function(context) 
    {
        cflog('Login Post route');

        var postdata = {};
        postdata.username = context.params.username;
        postdata.password = context.params.password;

        cflog(postdata);
        var serializedData = $(postdata).serialize(); 

        cflog(serializedData);
        cflog(JSON.stringify(postdata));
        //post submit login form
        //

        var request = $.ajax({
          url: "/apikey/login",
          type: "post",
          dataType: "json",
          contentType: "application/json",
          data: JSON.stringify(postdata),
          success: function(req){
                  cflog("success");
                  cflog(req);
                  //TODO - do we get apiuser back?... then what? Need knowledge of user to pass around?
                  //

                  

              },
          error:function(req){
                 cflog("failure");
                  cflog(req);
             }          
        });

        return false;
    });


    //
    // Control Screen (Admin)
    //
    this.get('#/controls', function() 
    {
        cflog('Controls Get route');
        //GLOBAL PAGE SETTINGS
        var data = { };

        $.extend(data, { admin: true});    //top nav
        $.extend(data, { controls: true,  title: "Admin - Controls" } );            //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#controls").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new ControlViewModel());
    });

    //
    // Create / Edit User
    //
    this.get('#/user/:userid', function() 
    {
        
        if(typeof this.params.userid == "undefined" || this.params.userid == "undefined")
        {
           cflog('user route : ADD : ');
        } else {
           cflog('user route : EDIT : ' + this.params.userid);
           
           //TODO - call server for user data ?
           //
           // I think we want to pass param in to ko model and let it acquire the data from server?
           //
        }

        //
        // Setup Nav
        // Setup Content
        // Bind Knockout to Data
        //

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { admin: true});    //top nav
        $.extend(data, {users: true, title: "Admin - Create / Edit User" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#user-edit").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new UserViewModel());
    });

    //
    // List Users
    //
    this.get('#/users', function() 
    {
        cflog('users route');

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { admin: true});    //top nav
        $.extend(data, { users: true, title: "Admin - List All Users" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#users-list").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new UsersViewModel());       
    });

    //
    // List Weeks
    //
    this.get('#/weeks', function() 
    {
        cflog('weeks route');

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { admin: true});                                       //top nav
        $.extend(data, {weeks: true, title: "Admin - List All Weeks" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#weeks-list").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new WeeksViewModel());
    });


    //
    // Scoreboard
    //
    this.get('#/scoreboard/:weeknumber', function() 
    {
        cflog('scoreboard weeknumber : ' + this.params.weeknumber);

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { admin: false, makeYourPicks: true,});                                       //top nav
        $.extend(data, {disablesubnav: true,  title: "Scoreboard - " + this.params.weeknumber });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#scoreboard").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new ScoreboardViewModel(this.params.weeknumber));
    });

    //
    // User List Weeks
    //
    this.get('#/playerweeks', function() 
    {
        cflog('playerweeks route');

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { admin: false, makeYourPicks: true,});                                       //top nav
        $.extend(data, {disablesubnav: true,  title: "Player - List All Weeks" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#player-weeks-list").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new PlayerWeeksViewModel());
    });

    //
    // Player Picks Week - player-picks
    // For a week - a player can select winners
    //
    this.get('#/playerpicks/:weeknumber', function() 
    {
        cflog('playerpicks weeknumber : ' + this.params.weeknumber);

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { admin: false, makeYourPicks: true,});                           //top nav
        $.extend(data, {disablesubnav: true,  title: "Player - Make Your Picks" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#player-picks").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new WeekPickViewModel(this.params.weeknumber));
    });

    //
    // Create / Edit Week
    //
    this.get('#/week/:weeknumber', function() 
    {
        
        if(typeof this.params.weeknumber == "undefined" || this.params.weeknumber == "undefined")
        {
           cflog('week route : ADD : ');
        } else {
          cflog('week route : EDIT : ' + this.params.weeknumber);
           
           //TODO - call server for week data
           //
           // does it go here? or simply in the init of the view model ?
        
        }

        //GLOBAL PAGE SETTINGS
        var data = { debug: true};

        //NAVIGATION
        $.extend(data, { admin: true});    //top nav
        $.extend(data, {weeks: true, title: "Admin - Create / Edit Week" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#week-edit").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new GamesViewModel(this.params.weeknumber));
    });

    //
    // Score Week
    //
    this.get('#/week/score/:weeknumber', function() 
    {

        if(typeof this.params.weeknumber == "undefined" || this.params.weeknumber == "undefined")
        {
           cflog('week score route : ADD : ');
           this.params.weeknumber = -1;
        } else {
           cflog('week score route : EDIT : ' + this.params.weeknumber);
           
           //TODO - call server for week data
           //
           // does it go here? or simply in the init of the view model ?
        }

        //GLOBAL PAGE SETTINGS
        var data = { debug: true };

        //NAVIGATION
        $.extend(data, { admin: true});    //top nav
        $.extend(data, {weeks: true, title: "Admin - Score Week" });      //sub nav
        handleNavigation(data);

        //CONTENT
        var contentsource = $("#week-score").html();
        var contenttemplate = Handlebars.compile(contentsource);
        $("#contentdiv").html(contenttemplate(data));

        //KO MODEL BIND
        ko.applyBindings(new GamesScoreViewModel(this.params.weeknumber));
    });

    //
    // Init:
    //
    this.get('', function() {
        this.app.runRoute('get', '#/home');
    });

}).run();  

</script>

</body>
</html>